// tcpudp.rs
use std::io::prelude::*;
use std::net::TcpStream;
use std::string::String;
use std::str::Bytes;
use std::vec::Vec;
use std::borrow::Borrow;
use std::io::Write;
use std::net::TcpListener;
use std::thread;
use std::result::Result;

pub fn tcpserver() {
    let listener = TcpListener::bind("127.0.0.1:51421").unwrap();
    println!("listening started, ready to accept");
    for stream in listener.incoming() {
        thread::spawn(|| {
            let mut stream = stream.unwrap();
            stream.write(b"Hello World\r\n").unwrap();
        });
    }
}

pub fn tcpclient() -> std::io::Result<()> {
    let mut stream = TcpStream::connect("127.0.0.1:51423")?;
    println!(" stream == {:?} ==", stream);
    let st = String::from("超人来了 主要的错误信息，“mismatched types”（类型不匹配），揭示了代码的核心问题。函数 plus_one 的定义说明它要返回一个 i32 类型的值，不过语句并不会返回值，使用空元组 () 表示不返回值。因为不返回值与函数定义相矛盾，从而出现一个错误。在输出中，Rust 提供了一条信息，可能有助于纠正这个错误：它建议删除分号，这会修复这个错误。");
    stream.write(st.as_bytes())?; //  as_bytes直接把字符串转成u8数组
    // stream.write(trans_vecu8(&st).borrow())?; // 第二种方式  //vec要将返回值所有权借出来才能被 流写入使用
    println!("write : {:?}", &st);
    stream.read(&mut [0; 128])?;
    stream.write("bye".as_bytes())?;
    Ok(())
} // the stream is closed here

// 字符串转换vec<u8>，其实是想要转换 [u8] 数组，字符串转换u8数组有as_bytes方法
// 此方法多余了,保留做代码样板
fn trans_vecu8(sendstr: &String) -> Vec<u8> {
    let v: Vec<u8> = Vec::new();
    let strBytes = sendstr.bytes();
    let strBytesLen = strBytes.len();
    let mut stru8Array: Vec<u8> = Vec::new();
    for pat in strBytes {
        stru8Array.push(pat as u8);
    }
    return stru8Array;
}


use std::net::UdpSocket;

pub fn udpserver() -> std::io::Result<()> {
    {
        let mut socket = UdpSocket::bind("127.0.0.1:51427").expect("couldn't bind to address 无法绑定当前地址");
        const buf_size: u32 = 2048;
        // Receives a single datagram message on the socket. If `buf` is too small to hold
        // the message, it will be cut off.
        let mut buf = [0; 2048];

        while true {
            let (amt, src) = socket.recv_from(&mut buf)?;
            // Redeclare `buf` as slice of the received data and send reverse data back to origin.
            let buf = &mut buf[..amt];
            let rcvstr = String::from_utf8(buf.to_vec()).unwrap();
            if rcvstr != "".to_string() {
                println!("udp send {:?}", "ok");
                socket.send_to("ok".as_bytes(), "127.0.0.1:51425").expect("couldn't send data 不能发送udp数据");
            }
            println!("udp buf {:?}", rcvstr);
            println!("udp src {:?}", &src);
            if rcvstr == "bye".to_string() {
                println!("udp say bye {:?}", rcvstr);
                break;
            }
            else {
                println!("udp not say bye {:?}", rcvstr);
            }
        }
        // buf.reverse();
        // socket.send_to(buf, &src)?;
        //let strx = "udp发送内容各种各种各种内容";
        //let sendstr = strx.as_bytes();
        //socket.send_to(&sendstr, "127.0.0.1:51425").expect("couldn't send data 不能发送udp数据");
    } // the socket is closed here
    Ok(())
}

pub fn udpclient() -> std::io::Result<()> {
    let mut socket = UdpSocket::bind("127.0.0.1:51427").expect("couldn't bind to address 无法绑定当前地址");
    let strx = "udp发送内容各种各种各种内容";
    let sendstr = strx.as_bytes();
    socket.send_to(&sendstr, "127.0.0.1:51425").expect("couldn't send data 不能发送udp数据");
    Ok(())
}

